﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Linq.Dynamic;
using System.Web.Mvc;
using SDT.Model;
using SDT.Lib.Common;
using SDT.Site.Properties;
using SDT.Site.ViewModels;
using SDT.Lib.Paging;
using System.Web.UI.WebControls;
using System.IO;
using System.Data.Linq;
using SDT.Lib.Helpers;
using SDT.Systems;
using System.Web.Security;

namespace SDT.Site.Controllers
{
    public class ProductController : Controller
    {
        SDTDataContext eDataContext = new SDTDataContext();
        //
        // GET: /Product/
        SDTDataContext db = new SDTDataContext();
        public ActionResult Index(int? id,int? catid,int? cityid, int? distrid, int? areaid, int? priceid,int? projectid, int? timeid, int? page)
        {
            if (page == null) page = 1; ;
            var pageIndex = page.Value - 1;
            var pageSize = Convert.ToInt32(UserState.getUserStateFromRequest("product.PageSize", "pageSize", Settings.Default.ProductPageSize));
            string order = UserState.getUserStateFromRequest("product.order", "order", "ID").ToString();
            string orderDir = UserState.getUserStateFromRequest("product.orderDir", "orderDir", "desc").ToString();
            int getbyTimeID = Utils.ParseInt(UserState.getUserStateFromRequest("product.TimeID", "ddlTimeCenter", 0));
            switch (order) { 
                case "AddDate":
                    orderDir = "desc";
                    break;
                case "nViews":
                    orderDir = "desc";
                    break;
                case "TotalCost":
                    orderDir = "asc";
                    break;
            }
            var postYN = Request.HttpMethod == "POST" ? true : false;

            ViewData["orderDir"] = orderDir;
            ViewData["order"] = order;
            ProductSearchModels p = new ProductSearchModels();
            p.AreaID = areaid;
            p.CategoryID = catid;
            p.CityID = cityid;
            p.DistrictID = distrid;
            p.PriceID = priceid;
            p.TimeID = postYN  ? getbyTimeID : timeid.Value;
            p.TypeID = id;
            p.ProjectID = projectid;
            p.Keyword = Request["key"] != null ? Request["key"] : string.Empty;
            p.Products = ProductManager.GetList(p.TypeID, p.CategoryID, p.CityID, p.DistrictID,
                p.AreaID, p.PriceID, p.ProjectID, p.TimeID, p.Keyword, 0, 1,
                order, orderDir, pageIndex, Utils.ParseInt(Settings.Default.ProductPageSize),Guid.Empty); // Added parameter Guide.Emty (Vietlv  - 12/09/2011)
            p.Times = Utils.StringToDictionaryIntString(Settings.Default.SearchByTime, ";");
            p.ImageUrl = Settings.Default.SiteRootUrl + Settings.Default.ProductRootUrl;
            p.ImagePath = Settings.Default.SiteRootPath + Settings.Default.ProductRootPath;
            
            if (p.CityID > 0)
            {
                p.Districts = ProductManager.GetDistrict(p.TypeID.Value, p.CategoryID.Value, p.CityID.Value);
                p.City = db.Cities.Where(e => e.ID == p.CityID).SingleOrDefault();
            }
            else {
                p.Districts = new List<District>(); 
            }
            p.Categories = id > 0 ? ProductManager.GetObjChildByType(id.Value) : null;
            p.Cities = ProductManager.GetCity(p.TypeID.Value, p.CategoryID.Value);
            p.ConvertPrices = ProductManager.GetConvertPrice(p.TypeID.Value);
            p.ConvertAreas = ProductManager.GetConvertArea(p.TypeID.Value);
            p.ProductTypes = db.ProductTypes.ToList();




            p.ProductType = db.ProductTypes.Where(e => e.ID == p.TypeID).SingleOrDefault();
            p.Category = db.ProductCategories.Where(e => e.ID == p.CategoryID).SingleOrDefault();
            p.District = db.Districts.Where(e => e.ID == p.DistrictID).SingleOrDefault();
            p.ConvertPrice = db.ConvertPrices.Where(e => e.ID == p.PriceID).SingleOrDefault();
            p.ConvertArea = db.ConvertAreas.Where(e => e.ID == p.AreaID).SingleOrDefault();
            p.Currencies = Utils.StringToDictionaryIntString(Settings.Default.ListCurrency, ",");

            return View(p);
        }
        public ActionResult Details(int id)
        {
            ProductDetailsModels p = new ProductDetailsModels();
            p.Product = db.Products.Where(e => e.ID == id).SingleOrDefault();
            string subPath = string.Format("{0}\\{1}\\{2}\\", p.Product.AddDate.Value.Year, p.Product.AddDate.Value.Month, p.Product.AddDate.Value.Day);
            string subUrl = string.Format("{0}/{1}/{2}/", p.Product.AddDate.Value.Year, p.Product.AddDate.Value.Month, p.Product.AddDate.Value.Day);

            p.ImageUrl = Settings.Default.SiteRootUrl + Settings.Default.ProductRootUrl + subUrl;
            p.ImagePath = Settings.Default.SiteRootPath + Settings.Default.ProductRootPath+subPath;
            p.GoogleAPI = Settings.Default.GoogleAPI;
            p.Directions = Utils.StringToDictionaryIntString(Settings.Default.ProductDirection, ",");

            p.ProductSearch = new ProductSearchModels();
            p.ProductSearch.Times = Utils.StringToDictionaryIntString(Settings.Default.SearchByTime, ";");
            if (p.Product.CityID > 0)
            {
                p.ProductSearch.Districts = ProductManager.GetDistrict(p.Product.TypeID, p.Product.CatID, p.Product.CityID);
                p.ProductSearch.City = p.Product.City;
            }
            else
            {
                p.ProductSearch.Districts = new List<District>();
            }
            p.ProductSearch.Categories = ProductManager.GetObjChildByType(p.Product.TypeID);
            p.ProductSearch.Cities = ProductManager.GetCity(p.Product.TypeID, p.Product.CatID);
            p.ProductSearch.ConvertPrices = ProductManager.GetConvertPrice(p.Product.TypeID);
            p.ProductSearch.ConvertAreas = ProductManager.GetConvertArea(p.Product.TypeID);
            p.ProductSearch.ProductTypes = db.ProductTypes.ToList();
            

            p.ProductSearch.ProductType = p.Product.ProductType;
            p.ProductSearch.Category = p.Product.ProductCategory;
            p.ProductSearch.District = p.Product.District;
            p.ProductSearch.ConvertPrice = p.Product.ConvertPrice1;
            p.ProductSearch.ConvertArea = p.Product.ConvertArea1;

            p.ProductSearch.AreaID =p.Product.ConvertArea;
            p.ProductSearch.CategoryID = p.Product.CatID;
            p.ProductSearch.CityID = p.Product.CityID;
            p.ProductSearch.DistrictID = p.Product.DistrictID;
            p.ProductSearch.PriceID = p.Product.ConvertPrice;
            p.ProductSearch.TimeID = 0;
            p.ProductSearch.TypeID = p.Product.TypeID;
            p.ProductSearch.ProjectID = 0;
            p.ProductSearch.PathTitle = p.Product.Title;
            p.Keyword = string.Empty;

            return View(p);
        }
        [HttpPost()]
        public ActionResult Search(ProductSearchModels p)
        {
            
            p.AreaID = Utils.ParseInt(Request["ddlArea"],0); ;
            p.CategoryID = Utils.ParseInt(Request["ddlCategory"], 0);
            p.CityID = Utils.ParseInt(Request["ddlCity"], 0);
            p.DistrictID = Utils.ParseInt(Request["ddlDistrict"], 0);
            p.PriceID = Utils.ParseInt(Request["ddlPrice"], 0);
            p.TimeID = Utils.ParseInt(Request["ddlTime"], 0);
            p.TypeID = Utils.ParseInt(Request["ddlType"],0);
            p.ProjectID = 0;
            p.Keyword = Request["txtKeyword"] != null ? Request["txtKeyword"] : string.Empty;

            var path = string.Format("index/{0}/{1}/{2}/{3}/{4}/{5}/{6}/{7}",
                   p.TypeID.HasValue ? p.TypeID.Value : 0,
                   p.CategoryID.HasValue?p.CategoryID.Value:0,
                   p.CityID.HasValue ? p.CityID.Value : 0,
                   p.DistrictID.HasValue ? p.DistrictID.Value : 0,
                   p.AreaID.HasValue ? p.AreaID.Value : 0,
                   p.PriceID.HasValue ? p.PriceID.Value : 0,
                   p.ProjectID.HasValue ? p.ProjectID.Value : 0,
                   p.TimeID.HasValue ? p.TimeID.Value : 0);
            if (p.Keyword != null && p.Keyword != string.Empty) path = path + "?key=" + p.Keyword;
            return RedirectToAction(path, "product");
        }
        public ActionResult List(int id, int? page)
        {
            if (page == null) page = 1; ;
            var pageIndex = page.Value - 1;
            var pageSize = Convert.ToInt32(UserState.getUserStateFromRequest("productlist.PageSize", "pageSize", Settings.Default.ProductPageSize));
            string order = UserState.getUserStateFromRequest("productlist.order", "order", "ID").ToString();
            string orderDir = UserState.getUserStateFromRequest("productlist.orderDir", "orderDir", "desc").ToString();
            ProductSearchModels p = new ProductSearchModels();
            var cp = db.Products.Where(e => e.ID == id).SingleOrDefault();
            p.AreaID =0;
            p.CategoryID = cp.CatID;
            p.CityID = 0;
            p.DistrictID = 0;
            p.PriceID = 0;
            p.TimeID =0;
            p.TypeID = cp.TypeID;
            p.ProjectID = 0;
            p.Keyword = string.Empty;
            p.AddBy =(System.Guid)cp.AddBy;
            p.Products = ProductManager.GetListProductOfUser(p.TypeID, p.CategoryID, p.CityID, p.DistrictID,
                 p.AreaID, p.PriceID, p.ProjectID, p.TimeID, p.Keyword, 0, 1,
                 order, orderDir, pageIndex, Utils.ParseInt(Settings.Default.ProductPageSize),p.AddBy);
            p.PathTitle = cp.ProductType.Name + " của " + cp.ContactName;
            p.ImageUrl = Settings.Default.SiteRootUrl + Settings.Default.ProductRootUrl;
            p.ImagePath = Settings.Default.SiteRootPath + Settings.Default.ProductRootPath;

            p.Categories = ProductManager.GetObjChildByType(cp.TypeID);
            p.Cities = ProductManager.GetCity(cp.TypeID, cp.CatID);
            p.ConvertPrices = ProductManager.GetConvertPrice(cp.TypeID);
            p.ConvertAreas = ProductManager.GetConvertArea(cp.TypeID);
            p.ProductTypes = db.ProductTypes.ToList();
            p.Districts = new List<District>();
            p.Times = Utils.StringToDictionaryIntString(Settings.Default.SearchByTime, ";");

            return View(p);
        }
        [ChildActionOnly]
        public ActionResult Lasted(int typeid, int? catid, int number, string order, string orderDir)
        {
            var p = new ProductListModels();
            var db = new SDTDataContext();
            var l = db.Products.Where(e => typeid > 0 ? e.TypeID == typeid : true)
                .Where(e => catid > 0 ? e.CatID == catid.Value : true)
                .Where(e=>e.PubYN==true)
                .OrderBy(string.Format("{0} {1}", order, orderDir)).Take(number).ToList();
            p.Products = l;
            p.ImageUrl = Settings.Default.SiteRootUrl + Settings.Default.ProductRootUrl;
            p.ImagePath = Settings.Default.SiteRootPath + Settings.Default.ProductRootPath;
            p.Currencies = Utils.StringToDictionaryIntString(Settings.Default.ListCurrency, ",");
            return View(p);
        }

        [ChildActionOnly]
        public ActionResult SearchHome(int typeid)
        {
            ProductSearchModels p = new ProductSearchModels();
            p.Categories = db.ProductCategories.Where(e => e.TypeID == typeid).OrderBy(string.Format("{0} {1}", "Priority", "asc")).ToList();
            p.ProductTypes = db.ProductTypes.OrderBy(string.Format("{0} {1}", "ID", "asc")).ToList();

            p.Cities = db.Cities.OrderBy(string.Format("{0} {1}", "Name", "asc")).ToList();
            p.ConvertAreas = db.ConvertAreas.Where(e => e.TypeID == typeid).ToList();
            p.ConvertPrices = db.ConvertPrices.Where(e => e.TypeID == typeid).ToList();
            return View(p);
        }
        [ChildActionOnly]
        public ActionResult OtherItems(int id, int number, string title)
        {
            var a = new ProductListModels();
            var current_product = db.Products.Where(e => e.ID == id).SingleOrDefault();
            var l = db.Products.Where(e => e.ProductCategory.ID == current_product.CatID)
                .Where(e => e.PubYN == true)
                .Where(e => e.ID != id)
                .Where(e => e.DistrictID==current_product.DistrictID).OrderByDescending(e => e.ID).Take(number).ToList(); ;
            ViewData["Title"] = title;
            a.Products = l;
            return View(a);
        }
        [ChildActionOnly]
        public ActionResult OtherItemsInCity(int id, int number, string title)
        {
            var p = new ProductListModels();
            var current_product = db.Products.Where(e => e.ID == id).SingleOrDefault();
            var l = db.Products.Where(e => e.ProductCategory.ID == current_product.CatID)
                .Where(e => e.PubYN == true)
                .Where(e => e.ID != id)
                .Where(e => e.CityID == current_product.CityID).OrderByDescending(e => e.ID).Take(number).ToList(); ;
            ViewData["Title"] = title;
            p.Products = l;
            p.ImageUrl = Settings.Default.SiteRootUrl + Settings.Default.ProductRootUrl;
            p.ImagePath = Settings.Default.SiteRootPath + Settings.Default.ProductRootPath;
            return View(p);
        }
        /// <summary>
        /// Poster: Tin cùng người đăng
        /// </summary>
        /// <param name="id"></param>
        /// <param name="number"></param>
        /// <param name="title"></param>
        /// <returns></returns>
        [ChildActionOnly]
        public ActionResult Poster(int id, string title)
        {
            var a = new ProductListModels();
            var current_product = db.Products.Where(e => e.ID == id).SingleOrDefault();
            var l = db.Products.Where(e => e.AddBy == current_product.AddBy)
                .Where(e => e.PubYN == true)
                .OrderByDescending(e => e.ID).ToList(); ;
            ViewData["Title"] = title;
            a.Products = l;
            a.CurrentProduct = current_product;
            return View(a);
        }
        [ChildActionOnly]
        public ActionResult LatestComments(int id, int number)
        {
            var latestC = new List<Comment>();
            try
            {
                latestC = ProductManager.GetComments(id, true, number).ToList();
            }
            catch (Exception exp)
            {
                ErrorLog.WriteLog(exp);
            }
            return PartialView(latestC);
        }
        [ChildActionOnly]
        public ActionResult Comment(int id)
        {
            CommentEditModels c = new CommentEditModels();
            c.ObjectID = id;
            var u = Membership.GetUser();
            if (u != null)
            {
                c.FullName = u.UserName;
                c.Email = u.Email;
            }
            return PartialView(c);
        }       
        
        #region Binhlv/ GetConvertPrice
        private ConvertPrice GetConvertPrice(decimal TotalPrice, int TypeProduct)
        {
            try
            {
                if (TotalPrice < 0) throw new NotSupportedException();
                var maxArea = eDataContext.ConvertPrices
                    .Where(e => e.TypeID == TypeProduct)
                    .OrderByDescending(e => e.MaxValue)
                    .FirstOrDefault();
                if (TotalPrice > maxArea.MaxValue)
                {
                    return maxArea;
                }
                var CurrentConvertPrice = eDataContext.ConvertPrices
                                        .Where(ca => ca.TypeID == TypeProduct)
                                        .Where(c => c.MinValue < TotalPrice && c.MaxValue >= TotalPrice) // Modified by Vietlv test vaule of boundaris (">" --> ">=")
                                        .FirstOrDefault();
                return CurrentConvertPrice;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion
        #region Binhlv/GetConvertAreaID
        private ConvertArea GetConvertArea(double Area, int TypeProduct)
        {
            try
            {
                if (Area < 0) throw new NotSupportedException();
                var maxArea = eDataContext.ConvertAreas
                    .Where(e => e.TypeID == TypeProduct)
                    .OrderByDescending(e => e.MaxValue)
                    .FirstOrDefault();
                if (Area > Convert.ToDouble(maxArea.MaxValue))
                {
                    return maxArea;
                }
                var CurrentConvertAreaID = eDataContext.ConvertAreas
                                        .Where(ca => ca.TypeID == TypeProduct)
                                        .Where(c => c.MinValue < (decimal)Area && c.MaxValue >= (decimal)Area) // Modified by Vietlv test vaule of boundaris (">" --> ">=")
                                        .FirstOrDefault();
                return CurrentConvertAreaID;

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion
    }
}
